##  Copyright (C) 2010 Fredrique Samuels, fredriquesamuels@gmail.com 
##
##
##  This program is free software; you can redistribute it and/or modify
##  it under the terms of the GNU General Public License as published by
##  the Free Software Foundation; either version 2 of the License, or
##  (at your option) any later version.
##
##  This program is distributed in the hope that it will be useful,
##  but WITHOUT ANY WARRANTY; without even the implied warranty of
##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##  GNU General Public License for more details.
##
##  You should have received a copy of the GNU General Public License
##  along with this program; if not, write to the Free Software
##  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.


import os

#===================================================================

"""
Get all the files and directories in the given directory
structure as a list

@param DIR : root dir
"""
def __getDirFiles(DIR):
   
    tmp = []
    FILES = []
    d = os.listdir(DIR)
    
    for f in d:
        
        n_dir = os.path.join(DIR,f)
        
        if os.path.isdir(n_dir):
            FILES += __getDirFiles(n_dir)
        else:
            FILES .append( n_dir.replace('\\','/') )
    return FILES


#===================================================================


def __getInnoInfo(output_iss = 'inno.iss',
                script_info = 'Autogenerated InnoScript v1.1',
                app_name = 'application',
                version = 'application v1.0',
                src_dir = None,
                dst_dir = None,
                uninstall_icon = None,
                desktop_sc = '',
                files = []):
    if src_dir is None:
        raise Exception("Must provide a src directory!!!! src_dir = 'c:/my_app'")
    if dst_dir is None:
        dst_dir = '{pf}/'+ app_name

    if not uninstall_icon is None:
        uninstall_icon = 'UninstallDisplayIcon='+uninstall_icon
    else:
        uninstall_icon = ""
    
    version = str(version)
    info = {'output_iss':output_iss,
            'script_info':script_info,
            'app_name':app_name,
            'version':version,
            'src_dir':src_dir,
            'dst_dir':dst_dir,
            'uninstall_icon':uninstall_icon,
            'files' : files
            }
    return info

#===================================================================

def __buildFileList(src_dir):
    files = __getDirFiles(src_dir)
    sd = src_dir.replace('\\','/')
   
    if not sd.endswith('/'):
        sd+='/'
    
    ret= []
        
    for f in files:
        
        dst = f.replace(sd,'')
        dst_p = dst.split('/')
        dst = ''
        del dst_p[-1]
        
        i = 0
        
        for d in dst_p:
          
            if i == 0:
                dst = d
                i+=1
                continue
            dst = os.path.join(dst,d)
            i+=1
        
        dst = dst.replace('\\','/')
        if len(dst)>1:
            dst='/'+dst
        ret.append((f,dst,))
    return ret

#===================================================================

def genInnoScript(output_iss = 'inno.iss',
                script_info = 'Autogenerated InnoScript v1.1',
                app_name = 'application',
                version = 'application v1.0',
                src_dir = None,
                dst_dir = None,
                uninstall_icon = None,
                desktop_sc = '',
                files = []):

    info = __getInnoInfo(src_dir=src_dir,
                       dst_dir=dst_dir,
                       app_name=app_name,
                       version=version,
                       output_iss=output_iss,
                       files = __buildFileList(src_dir))
    """
    Generate an InnoScript from the
    given parameters
    """

    _f = ''
    
    for f in info['files']:
        _info = {'file':f[0],'dst':f[1]}
        _f+='Source: \"%(file)s\"; DestDir: \"{app}%(dst)s\"\n' % _info
    info['files'] = _f
    
    template = """
; -- %(output_iss)s --
; %(script_info)s

; SEE THE DOCUMENTATION FOR DETAILS ON CREATING .ISS SCRIPT FILES!

[Setup]
AppName=%(app_name)s
AppVerName=%(version)s
DefaultDirName=%(dst_dir)s
DisableProgramGroupPage=yes
; ^ since no icons will be created in "{group}", we don't need the wizard
;   to ask for a group name.
%(uninstall_icon)s

[Files]
%(files)s

;[Icons]
;Name: "{commonprograms}\My Program"; Filename: "{app}\MyProg.exe"
;Name: "{userdesktop}\My Program"; Filename: "{app}\MyProg.exe"

[Run]

"""
    
    iss =  template % info
    fh = open(info['output_iss'],'w')
    fh.write(iss)
    fh.close()
    #TODO

#===================================================================

def example():
    src_dir = 'c:/MingW/'
    dst_dir = 'c:/MingW/'
    app = "MingW32"
    version = "MingW32_build_June_2008"
    


    genInnoScript(output_iss = 'MingW.iss',
                  src_dir = src_dir,
                  dst_dir = dst_dir,
                  app_name = app,
                  version = version)

#===================================================================

def main():
    example()

if __name__ == '__main__':
    main()

